<?php
	session_start();
// Below is a very simple PHP 5 script that implements the RPX token URL processing.
// The code below assumes you have the CURL HTTP fetching library.
	require_once '../dev_con.inc.php';
	require_once '../functions/class.query.inc.php';	
	$queryData = new queryData();
	$queryData->baseConfig();
	$rpxApiKey = USE_OPENID_APIKEY;
		
	if(isset($_POST['token'])) {
	
		/* STEP 1: Extract token POST parameter */
		$token = $_POST['token'];
		
		/* STEP 2: Use the token to make the auth_info API call */
		$post_data = array('token' => $_POST['token'],
						 'apiKey' => $rpxApiKey,
						 'format' => 'json');
		
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_URL, 'https://rpxnow.com/api/v2/auth_info');
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$raw_json = curl_exec($curl);
		curl_close($curl);
		
		/* STEP 3: Parse the JSON auth_info response */
		$auth_info = json_decode($raw_json, true);
		/* STEP 3 Continued: Extract the 'identifier' from the response */		
		if ($auth_info['stat'] == 'ok') {
			$profile = $auth_info['profile'];
			$identifier = md5($profile['identifier']);
			
			if (isset($profile['email'])) {
				$email = $profile['email'];
			}
			
			if (isset($profile['photo'])) {
				$photo_url = $profile['photo'];
			}
			
			if (isset($profile['displayName'])) {
				$name = $profile['displayName'];
			}
			
			$sql1 = "SELECT * FROM `tbl_login` WHERE namauser='".mysql_real_escape_string($email)."' LIMIT 1";
			$qry1 = mysql_query($sql1);
			$row1 = mysql_fetch_object($qry1);
			if (!empty($row1->id_user)) {
				if ($row1->id_user=='1') {
					$_SESSION['isroot'] = true;	
				} else {
					unset($_SESSION['isroot']);	
				}
			} else {
				$tanggal = date("Y-m-d-H-i-s");
				$sql = "INSERT INTO tbl_login VALUES(NULL,'".$identifier."','".$name."','".$identifier."','1','openid[break]','".$tanggal."','".$tanggal."')";
				$qry = mysql_query($sql);
				
			}
			
			$sql1 = "SELECT * FROM `tbl_login` WHERE namauser='".mysql_real_escape_string($identifier)."' AND passuser='".mysql_real_escape_string($identifier)."' LIMIT 1";
			$qry1 = mysql_query($sql1);
			$row1 = mysql_fetch_object($qry1);
			if (!empty($row1->id_user)) {
				$_SESSION['sesi_login'] = true;
				$_SESSION['author'] = strtolower($username);
				$_SESSION['id_char'] = $row1->id_user;
				$_SESSION['admin_type'] = $row1->type_user;	
			}
		
			header("Location:../index.php");
		
		/* an error occurred */
		} else {
		  // gracefully handle the error. Hook this into your native error handling system.
		  echo 'An error occured: ' . $auth_info['err']['msg'];
		}
	}
?>